package com.neusoft.elmboot.controller;


import com.auth0.jwt.interfaces.Claim;
import com.github.pagehelper.PageInfo;
import com.neusoft.elmboot.common.Result;
import com.neusoft.elmboot.dto.BusinessReqDto;
import com.neusoft.elmboot.dto.LoginReqDto;
import com.neusoft.elmboot.dto.UserReqDto;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.Role;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;



    @PostMapping("/login")
    public Result login(@RequestBody LoginReqDto reqDto) {

        String source = reqDto.getSource();
        if(null != source && !"pc".equalsIgnoreCase(source.trim())) {
            String code = reqDto.getCode();

            if (null == code || "".equals(code.trim())) {
                return Result.fail(500,"验证码不能为空！");
            }

            String codeRedis = (String)redisTemplate.opsForValue().get("elm:user:login:verifycode");
            if(!code.trim().equalsIgnoreCase(codeRedis)) {
                return Result.fail(500,"验证码出错：验证码过期或输入错误！");
            }
        }

        User  u = userService.login(reqDto);
        Map<String,Object> retMap = new HashMap<>();
        if (u != null) {
            u.setPassword(null);// 安全起见，将密码设为空，返回给前端。
            retMap.put("user",u);
            retMap.put("token", JWTUtil.generateToken(u.getUserId(),""));
            return Result.success(retMap,"登录成功！");
        }

        return Result.fail(500,"登录失败，请检查用户名和密码！");
    }

    @GetMapping("/info")
    public Result getUserInfo(String token) {

        String userId = JWTUtil.getUsernameFromToken(token);
        User user = userService.getUserByUserId(userId);

        List<String> perms = new ArrayList<>();
        Claim authorities = JWTUtil.getClaim(token, "authorities");
        System.out.println("-------authorities:"+authorities.asString());
        if("*".equals(authorities.asString())) {
            perms.add("*");
        } else {
            perms = userService.getPermApisByUserId(userId);
        }
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("name",user.getUserName()); // 用户名【昵称】
        retMap.put("avatar",user.getUserImg()); // 用户头像
        retMap.put("perms",perms); // 用户权限列表

        return Result.success(retMap,"查询用户信息成功！");

    }

    @PostMapping("/logout")
    public Result logout() {
        return Result.success("OK","用户退出成功！");
    }


    @RequestMapping("/getUserById")
    public Result getUserById(User user) throws Exception {
        Integer  x = userService.getUserById(user.getUserId());

        if (x != null && x > 0) {
            return Result.success(x,"成功！");
        }

        return Result.fail(500,"失败，请检查用户编号！");
    }

    @RequestMapping("/saveUser")
    public int saveUser(User user) throws Exception{
        return userService.saveUser(user);
    }



    @PostMapping("/assignRole")
    public Result assignRole(@RequestBody Map<String,Object> params) {
        // 调用业务层（service层）来处理业务逻辑！
        Map<String,Object> retMap = new HashMap<>();

        int x = userService.assignRole(params);
        retMap.put("x", x);

        return Result.success(retMap,"分配角色成功！");
    }


    /**
     * 用户列表查询接口
     * @return
     */
    @GetMapping("/list")
    public Result list(UserReqDto params) {
        // 调用业务层（service层）来处理业务逻辑！
        Map<String,Object> retMap = new HashMap<>();

        PageInfo<User> page = userService.getUserPage(params);
        retMap.put("data",page.getList());
        retMap.put("total", page.getTotal());

        return Result.success(retMap,"用户列表查询成功！");
    }


    /**
     * 新增用户接口
     * @return
     */
    @PostMapping("/create")
    public Result add(@RequestBody UserReqDto params) {
        System.out.println("-----------user/create...");
        // 调用业务层（service层）来处理业务逻辑！
        Integer x = userService.addUser(params);

        return Result.success(x,"新增用户成功！");
    }


    @GetMapping("/detail")
    public Result detail(String id) {
        User user = userService.getUserByUserId(id);
        return Result.success(user,"查看用户详情成功");
    }


    /**
     * 更新用户接口
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody UserReqDto params) {
        System.out.println("-----------user/update...");

        // 调用业务层（service层）来处理业务逻辑！
        Integer x = userService.updateUser(params);

        return Result.success(params.getUserId(),"更新用户成功！");
    }

    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable String id) {
        int x = userService.deleteUser(id);
        return Result.success(id,"用户删除成功！");
    }

    @GetMapping("/roleInfo/{id}")
    public Result roleInfo(@PathVariable Integer id) {
        Role x = userService.selectRoleByUserId(id);
        return Result.success(x,"用户角色查询成功！");
    }



}
